package com.wangjie.simple;

import java.util.Arrays;

/**
 * @author jieshao
 * @date 2022/5/30 10:03
 *
 * 1991. 找到数组的中间位置
 *
 * 左侧和为 sum，总和为 total，则 sum = total - sum - nums[i]，即 2 * sum + nums[i] = total
 */
public class Test06 {
    public static void main(String[] args) {
        int[] arr = {2, 3, -1, 8, 4};
        int res = findMiddleIndex(arr);
        System.out.println(res);
    }

    public static int findMiddleIndex(int[] nums) {
        int total = Arrays.stream(nums).sum();
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (2 * sum + nums[i] == total) {
                return i;
            }
            sum += nums[i];
        }
        return -1;
    }
}